<?php
// +----------------------------------------------------------------------
// |评论模型
// +----------------------------------------------------------------------
// |Data:2016-06-28 上午10:04
// +----------------------------------------------------------------------
// |Author: 吕志雄 <870923001@qq.com>
// +----------------------------------------------------------------------
namespace Wap\Model;
use Common\Model\CommonModel;

class CommentModel extends CommonModel{
    protected $tableName = 'comment';

    /**
     * 获取分数数量
     * @param $shop_id 店铺ID
     * @return bool
     */
    public function getScoreNumList($shop_id){
        if(empty($shop_id)) return false;
        return $this->where('shop_id='.$shop_id)->field('score')->select();
    }

    /**
     * 计算店铺分数
     * @param $shop_id
     * @return bool|float
     */
    public function getShopScore($shop_id){
        if(empty($shop_id)) return false;
        $totalNum = $this->where('shop_id='.$shop_id)->count('order_id');
        $totalScore = $this->where('shop_id='.$shop_id)->sum('score');
        if(intval($totalNum) == 0 || intval($totalScore) == 0){
            return 0;
        }else{
            return number_format($totalScore/$totalNum,1);
        }
    }

    /**
     * 获取靠前的评论
     * @param $shop_id
     * @param int $limit
     * @return bool
     */
    public function getTopCommentList($shop_id,$limit=5){
        if(empty($shop_id)) return false;
        return $this->where('shop_id='.$shop_id)->field('nickname,content,add_time,replay_content,score')->order('add_time desc,replay_time desc')->limit($limit)->select();
    }

    /**
     * 评论操作
     * @param $order_id
     * @param $data
     * @return bool
     */
    public function doComment($order_id,$data){
        if(empty($order_id) || empty($data) || !is_array($data)) return false;
        M()->startTrans();
        $res = M('order')->where('id='.$order_id)->setField('is_comment',1);
        $res_2 = $this->add($data);
        $res_3 = M('shop')->where('id='.$data['shop_id'])->setInc('comment_num');
        if($res && $res_2 && $res_3){
            M()->commit();
            return true;
        }else{
            M()->rollback();
            return false;
        }
    }
}
?>